<style lang="less">
@import url(../../../node_modules/@wangeditor/editor/dist/css/style.css);

.publish-article {
  padding-top: 15px;

  .publish-article-header {
    .opt {
      margin-bottom: 15px;
    }

    .my-select {
      margin-left: 15px;
    }

    .preview-img {
      width: 360px;
      height: 180px;
      border-radius: 4px;
    }

    .el-upload-list {
      display: none;
    }
  }
}
</style>
<template>
  <div class="publish-article">
    <header class="publish-article-header">
      <el-form :model="article" label-width="100px">
        <el-form-item label="文章标题">
          <el-input v-model="article.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>

        <el-form-item label="作者">
          <el-input v-model="article.author" placeholder="请输入作者" :disabled="isNormalUser"></el-input>
        </el-form-item>

        <el-form-item label="分类">
          <el-select @change="changeCateFn" v-model="article.cate" placeholder="请选择一级分类">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <el-select v-if="category_options.length != 0" class="my-select" v-model="article.category"
            placeholder="请选择二级分类">
            <el-option v-for="item in category_options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章内容">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar style="border-bottom: 1px solid #dcdfe6" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig" :mode="mode"
              @onCreated="onCreated" />
          </div>
        </el-form-item>

        <el-form-item label="封面图片">
          <div style="display: flex;">
            <el-upload class="upload-demo" drag action="" :on-change="changeFn" :auto-upload="false" accept="image/*">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

            <div v-if="src" style="text-align: center; margin-left: 15px">
              <img class="preview-img" :src="src" alt="封面预览">
            </div>
          </div>
        </el-form-item>

        <el-form-item label="标签">
          <el-input v-model="article.tag" placeholder="请输入标签，多个标签用逗号分隔"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitFn">发布文章</el-button>
        </el-form-item>
      </el-form>
    </header>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { listCate, uploadPhoto, isLogined, publishArticle, host } from "../../api/index"

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      article: {
        title: "",
        author: "",
        cate: "",
        category: "",
        tag: "",
      },
      options: [], // 一级分类选项（动态加载）
      category_options: [],
      editor: null,
      html: '',
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: `${host}/api/photo/upload_img`,
            fieldName: 'photo',
          }
        }
      },
      mode: 'default',
      src: "",
      cateArr: [],
      file: null,
      isNormalUser: false
    }
  },
  computed: {
    userRole() {
      return localStorage.getItem("USER_ROLE") || '0'
    }
  },
  methods: {
    async uploadPhotoFn() {
      if (this.file) {
        let formData = new FormData()
        formData.append("photo", this.file)
        return await uploadPhoto(formData)
      }
    },
    changeCateFn(value) {
      this.article.cate = value
      let arr = this.cateArr.filter(item => {
        return item.cate == value
      })
      let newArr = arr.map(item => {
        return {
          value: item.cate_name,
          label: item.cate_name,
        }
      })
      this.category_options = newArr
      this.article.category = arr[0] && arr[0].cate_name
    },
    async listCateFn() {
      await listCate().then(resData => {
        if (resData.code == 200) {
          let { result } = resData
          this.cateArr = result
          const parentCates = new Set()
          result.forEach(item => {
            if (item.cate) {
              parentCates.add(item.cate)
            }
          })
          this.options = Array.from(parentCates).map(cate => ({
            value: cate,
            label: cate
          }))
        }
      })
    },
    onCreated(editor) {
      this.editor = Object.seal(editor)
    },
    changeFn(info) {
      let file = info.raw
      const reader = new FileReader()
      reader.onload = () => {
        this.src = reader.result
      }
      if (file) {
        reader.readAsDataURL(file)
        this.file = file
      }
      return false
    },
    async submitFn() {
      let html = this.html
      let result = await this.uploadPhotoFn()
      let { title, author, cate, category, tag } = this.article

      if (title && author && cate && category && tag && html && result && result.picUrl) {
        await publishArticle({
          title,
          author,
          cate,
          cate_name: category,
          content: html,
          src: result.picUrl,
          tag
        })
          .then(resData => {
            if (resData.code == 200) {
              this.$message({ type: "success", message: resData.msg })
              this.$router.push({ path: "/article_list" })
            } else {
              this.$message({ type: "error", message: resData.msg })
            }
          })
      } else {
        this.$message({ type: "error", message: "请填写完整信息" })
      }
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy()
  },
  created() {
    this.$store.commit("addTab", this.$route)
    this.listCateFn()
    // 判断是否为普通用户
    const role = localStorage.getItem("USER_ROLE") || '0'
    this.isNormalUser = role !== '1'
    // 如果是普通用户，自动设置作者为用户名
    if (this.isNormalUser) {
      const username = localStorage.getItem("USERNAME") || ""
      this.article.author = username
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  },
  async beforeRouteEnter(to, from, next) {
    let token = localStorage.getItem("AUTO_TOKEN")
    if (token) {
      await isLogined({ token })
        .then(resData => {
          if (resData && resData.msg == '用户登录在线状态') {
            next()
          } else {
            if (confirm("您还没有登录，是否跳转")) {
              next({ path: "/login" })
            } else {
              next({ path: "/article_list" })
            }
          }
        })
        .catch(() => {
          if (confirm("您还没有登录，是否跳转")) {
            next({ path: "/login" })
          } else {
            next({ path: "/article_list" })
          }
        })
    } else {
      if (confirm("您还没有登录，是否跳转")) {
        next({ path: "/login" })
      } else {
        next({ path: "/article_list" })
      }
    }
  },
}
</script>
